import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import moment from 'moment'
import { message, Skeleton } from 'antd'
import ReactEchartsCore from 'echarts-for-react/lib/core'
import * as echarts from 'echarts/core'
import { BarChart } from 'echarts/charts'
import { TooltipComponent, TitleComponent, LegendComponent, GridComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import style from './Style.module.less'
import { addResizeEvent, delResizeEvent } from '@redux/actions'
import { colors } from '@js/config'
echarts.use([BarChart, TooltipComponent, TitleComponent, CanvasRenderer, LegendComponent, GridComponent])
class NumberStatistic extends Component {
  state = {
    colors,
    total: 0,
    year: moment().year(),
    ready: true,
    loading: false,
    acceptList: [],
    closeList: [],
    docketList: [],
    beginTime: moment('2012-01-01 00:00:00'),
    endTime: moment(`${moment().year()}-12-31 23:59:59`)
  }

  getPercent (v) {
    const { total } = this.state
    if (v && total) {
      return Math.round(v / total * 10000) / 100 + '%'
    }
  }

  // 获取全部数据
  getTotalData () {
    this.setState({ loading: true })
    Promise.all([this.getData('accept_datetime'), this.getData('docket_datetime'), this.getData('closure_datetime')])
      .then(res => {
        this.setState({ loading: false })
      }).catch(() => this.setState({ loading: false }))
  }

  // 获取数据
  getData (type) {
    const { beginTime, endTime } = this.state
    return this.$get('/api/xapc/casestat', {
      type,
      begintime: Math.floor(beginTime / 1000),
      endtime: Math.floor(endTime / 1000),
      group: 'year'
    }).then(res => {
      if (res.status === 1) {
        res.data.list.sort((a, b) => a.title - b.title)
        if (type === 'accept_datetime') {
          this.setState({
            acceptList: res.data.list
          })
        } else if (type === 'closure_datetime') {
          this.setState({
            closeList: res.data.list
          })
        } else if (type === 'docket_datetime') {
          this.setState({
            docketList: res.data.list
          })
        }
      } else {
        message.warning(res.message)
      }
    })
  }

  // 获取配置
  getOptions () {
    const labels = this.state.acceptList.map(li => li.title)
    return {
      grid: {
        left: 48,
        right: 0,
        top: 40,
        bottom: 30
      },
      legend: {
        show: true,
        left: 8,
        icon: 'roundRect',
        itemWidth: 8,
        itemHeight: 8,
        itemGap: 24,
        textStyle: {
          color: '#7E889C'
        }
      },
      tooltip: {},
      xAxis: {
        type: 'category',
        data: labels,
        axisLine: {
          lineStyle: {
            color: '#ddd'
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#8f949e'
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#8f949e'
        },
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        },
        minInterval: 1
      },
      series: [{
        name: '收案数',
        data: this.state.acceptList.map(li => li.caseno),
        type: 'bar',
        barWidth: '20%',
        color: '#3b98ff'
      }, {
        name: '立案数',
        data: this.state.docketList.map(li => li.caseno),
        type: 'bar',
        barWidth: '20%',
        color: '#29ba51'
      }, {
        name: '结案数',
        data: this.state.closeList.map(li => li.caseno),
        type: 'bar',
        barWidth: '20%',
        color: '#f9c514'
      }]
    }
  }

  // 点击图标
  clickChart ({ seriesType, name, seriesName }) {
    const typeMap = {
      收案数: 'accept_datetime',
      立案数: 'docket_datetime',
      结案数: 'closure_datetime'
    }
    const date = moment(`${name}-01-01 00:00:00`)
    const beginTime = moment(date)
    const endTime = moment(date)
    endTime.add(1, 'y')
    endTime.subtract(1, 's')
    this.props.addWindow({
      id: 'CaseStatistic',
      title: '案件统计',
      componentName: 'CaseStatistic',
      forceRefresh: true,
      meta: {
        formData: {
          type: typeMap[seriesName],
          beginTime,
          endTime
        }
      }
    })
  }

  componentDidMount () {
    this.getTotalData()
    this.props.addResizeEvent({
      name: 'year-numberStatistic',
      handle: () => this.setState({ ready: false }, () => {
        setTimeout(() => {
          this.setState({ ready: true })
        }, 100)
      })
    })
  }

  componentWillUnmount () {
    this.props.delResizeEvent('year-numberStatistic')
  }

  render () {
    return (
      <div className={style.block}>
        <div className={style['block-header']}>
          <span className={style['block-header__title']}>年度案件数统计</span>
        </div>
        <div className={style['block-body']}>
          <Skeleton loading={this.state.loading}>
            <div className={style['chart-box']}>
              {this.state.ready ? <ReactEchartsCore style={{ width: '100%', height: '100%' }} echarts={echarts} option={this.getOptions()} onEvents={{ click: p => this.clickChart(p) }} /> : null}
            </div>
          </Skeleton>
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addResizeEvent: i => dispatch(addResizeEvent(i)),
    delResizeEvent: i => dispatch(delResizeEvent(i))
  }
})

export default connect(mapState, mapDispatch)(NumberStatistic)
